/// <reference path="../node_modules/@types/socket.io/index.d.ts" />

import crypto from '../utils/crypto';
import db from '../utils/db';
import roomMgr from './roommgr';
import userMgr from './usermgr';
import tokenMgr from './tokenmgr';
import * as socketIO from 'socket.io';


//获取类型声明//
import configs_win from '../configs_win';
const GAME_SERVER_TYPE = configs_win.game_server();
type game_server_config = typeof GAME_SERVER_TYPE;
//获取类型声明//




// declare namespace SocketIO{
//     interface Server{

//     }
// }




let io:SocketIO.Server = null;

export default class Socket_service{
    
    static start(config: game_server_config, mgr?){

        io = socketIO(config.CLIENT_PORT);
        
        io.sockets.on('connection', socket => {

            socket.on('login', (data: ret&string) => {

                data = JSON.parse(data);
                if(socket.userId != null){
                    //已经登录过的忽略
                    return;
                }
                
                const token = data.token;
                let roomId = data.roomid;
                const time = data.time;
                const sign = data.sign;
                console.log(token, roomId, time, sign);

                if(token == null || roomId == null || sign == null || time == null){
                    socket.emit('login_result', {
                        errcode: 1,
                        errmsg: 'token 或 roomId 或 sign 或 time 为空 ',
                    });
                    return;
                }

                //检查参数是否被篡改
                const md5 = crypto.md5(roomId + token + time + config.ROOM_PRI_KEY);
                if(md5 != sign){
                    socket.emit('login_result', {
                        errcode: 2,
                        errmsg: '登录失败，sign无效'
                    });
                    return;
                }

                //检查token是否有效
                if(tokenMgr.isTokenValid(token) == false){
                    socket.emit('login_result', {
                        errcode: 3,
                        errmsg: 'token过期'
                    });
                    return;
                }


                //检查房间合法性
                const userId = tokenMgr.getUserID(token);
                roomId = roomMgr.getUserRoom(userId);

                userMgr.bind(userId, socket);
                socket.userId = userId;

                //返回房间信息
                const roomInfo = roomMgr.getRoom(roomId);
                const seatIndex = roomMgr.getUserSeat(userId);
                roomInfo.seats[seatIndex].ip = socket.handshake.address;

                let userData = null;
                let seats:seat[] = [];

                for(let i = 0; i < roomInfo; i++){
                    let rs = roomInfo.seats[i];
                    let online = false;
                    if(rs.userId > 0){
                        online = userMgr.isOnline(rs.userId);
                    }
                    seats.push({
                        userId: rs.userId,
                        ip: rs.ip,
                        score: rs.score,
                        name: rs.name,
                        online: online,
                        ready: rs.ready,
                        seatIndex: i,
                    });
                    if(userId == rs.userId){
                        userData = seats[i];
                    }
                }

                //通知前端
                const ret: ret = {
                    errcode: 0,
                    errmsg: 'ok',
                    data: {
                        roomId: roomInfo.id,
                        conf: roomInfo.conf,
                        numOfGames: roomInfo.numOfGames,
                        seats: seats,
                    }
                };
                socket.emit('login_result', ret);

                //通知其他前端
                userMgr.broacastInRoom('new_user_comes_push', userData, userId);

                socket.gameMgr = roomInfo.gameMgr;

                //玩家上线强制设置为true
                socket.gameMgr.setReady(userId);
                socket.emit('login_finished');

                if(roomInfo.dr != null){
                    const dr = roomInfo.dr;
                    const ramainTime = (dr.endTime - Date.now()) / 1000;
                    const data: actionState = {
                        time: ramainTime,
                        states: dr.states,
                    };
                    userMgr.sendMsg(userId, 'dissolve_notice_push', data);
                }
            });
            


        });

        console.log('游戏socket服务器运行在：' + config.CLIENT_PORT);
    }
}